import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
//导入node.js中的path
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],

  resolve: {
		alias: {   //配置路径别名
			'@': path.resolve(__dirname, 'src'),
			'@icons': path.resolve(__dirname, 'src/icons'),
		}
	},

	server: {
		proxy: {
		  '/api': {
			target: ' http://localhost:8080/', // 凡是遇到 /api 路径的请求，都映射到 target 属性
			changeOrigin: true,
			rewrite: path => path.replace(/^\/api/, '') // 重写 api 为 空，就是去掉它
		  }
		}
	},
	// tailwind CSS 优化配置
	optimizeDeps: {
		include: ['@fortawesome/fontawesome-free'],
	},

	build: {
  target: ["chrome89", "edge89", "firefox89", "safari15"],
  copyPublicDir: true,
  chunkSizeWarningLimit: 1500,
  rollupOptions: {
    output: {
      manualChunks(id) {
        if (id.includes('node_modules')) {
          const match = id.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/);
          if (match) {
            const libName = match[1];
            // 合并小型库
            return ['lodash', 'date-fns'].includes(libName) 
              ? 'core-utils' 
              : libName;
          }
        }
      },
      chunkFileNames: (chunkInfo) => {
        // 分类处理 vendor 和业务代码
        if (chunkInfo.facadeModuleId?.includes('node_modules')) {
          return 'js/vendor/[name].[hash].js';
        }
        
        // 业务代码按来源目录组织
        const segments = chunkInfo.facadeModuleId?.split(/[\\/]/) || [];
        const dirName = segments.length > 1 
          ? segments[segments.length - 2] 
          : 'common';
        return `js/${dirName}/[name].[hash].js`;
      }
    }
  }
}
})
